package com.jun.controller.user;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jun.pojo.entity.SysOrder;
import com.jun.pojo.entity.SysOrderUser;
import com.jun.pojo.vo.R;
import com.jun.pojo.vo.SysOrderUserVo;
import com.jun.pojo.vo.SysOrderVo;
import com.jun.service.SysOrderService;
import com.jun.service.SysOrderUserService;
import com.jun.util.QRCodeUtil;
import com.jun.util.SnowflakeUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/sysOrder")
public class SysOrderController implements InitializingBean {
  private static Integer orderId;
  @Autowired
  private SysOrderService sysOrderService;
  @Autowired
  private SysOrderUserService sysOrderUserService;
  @Autowired
  private ObjectMapper objectMapper;

  /**
   * 获取数据库id最大值
   */
  @Override
  public void afterPropertiesSet() {
    Integer maxId = sysOrderService.getMaxId();
    // 如果数据库为空，最大值为0
    orderId = maxId != null ? maxId : 0;
  }

  @GetMapping(path = {"/{userId}", "/"})
  public R getSysOrder(@PathVariable(value = "userId", required = false) Integer userId) {
    if (userId != null) {
      List<SysOrderUserVo> sysOrderUserVos = sysOrderUserService.selectByUserId(userId);
      return new R(sysOrderUserVos);
    }
    return new R();
  }

  @PostMapping
  @Transactional
  public R addOrder(@RequestBody Map<Integer, SysOrderVo> map,
                    @RequestParam("userId") Integer userId,
                    @RequestParam("sumPrice") BigDecimal sumPrice) throws IOException {
    // 存放 SysOrder 对象
    List<SysOrder> sysOrderList = new ArrayList<>();

    // 订单id采用最大id+1
    // 批量插入SysOrder的id保持一致
    orderId++;

    map.forEach((k, v) -> {
      Map<String, Object> obj = v.getObj();
      int shopId = (int) obj.get("id");
      int buy = v.getBuy();

      SysOrder sysOrder = new SysOrder()
          .setId(orderId)
          .setShopId(shopId)
          .setBuy(buy);
      sysOrderList.add(sysOrder);
    });

    SysOrderUser sysOrderUser = new SysOrderUser()
        .setOrderId(orderId)
        .setUserId(userId)
        .setQrcode("/qrcode/" + orderId)
        .setSumPrice(sumPrice)
        .setCreateTime(LocalDateTime.now());

    sysOrderService.saveBatch(sysOrderList);
    sysOrderUserService.save(sysOrderUser);

    // 将sysOrderList序列化
    String json = objectMapper.writeValueAsString(sysOrderList);

    // 二维码保存到本地
    QRCodeUtil.generateQRCodeToLocal(json, orderId.toString());

    return new R(orderId);
  }


}
